package com.blog.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;



public class DBUtils {

    private static Properties properties=new Properties();

    static{
        InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
        try {
            properties.load(is);
            //加载数据库驱动
            Class.forName(properties.getProperty("driver"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }



    //获取数据库连接
    public static Connection getConnection() throws SQLException {
        String url=properties.getProperty("url");
        String username=properties.getProperty("username");
        String password=properties.getProperty("password");
        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    //释放数据库连接
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
    }


}
